<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2018/3/23
 * Time: 14:08
 */

namespace app\api\model;
use app\common\lib\exception\ApiException;
use app\common\lib\wechat\WxCommon;
use think\Model;
use think\Log;
use think\Db;
use app\admin\model\Lesson as LessonModel;

class Teacher extends Model
{
    /**
     * 教师费用提现
     * @param int user_id 用户id *必传
     * @param int bank_account_id 银行账户id *必传
     * @param float total_amount 提现金额 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function teacherCostWithdrawals(){
        $request = $_POST;

        $wx = new WxCommon();

        /*$request['user_id'] = 1;
        $request['bank_full_name'] = '王柯';
        $request['bank_code'] = '1003';
        $request['bank_card'] = '6217003810062587293';
        $request['total_amount'] = 2;*/

        if(!isset($request['user_id'])){
            throw new ApiException('user_id（用户id） is not found！',404);
        }

        if(!isset($request['bank_account_id'])){
            throw new ApiException('bank_account_id（银行账户id） is not found！',404);
        }

        if(!isset($request['total_amount'])){
            throw new ApiException('total_amount（提现金额） is not found！',404);
        }

        if($request['total_amount'] < 1 || $request['total_amount'] > 5000000){
            return show(config('code.error'),'单笔提现必须大于等于0.01元且小于等于5万元！');
        }

        //用户银行账户信息
        $bank_account_info = db('bank_account')->where('user_id='.$request['user_id'].' AND id='.$request['bank_account_id'])->find();

        $request['bank_card'] = $bank_account_info['bank_card'];
        $request['bank_full_name'] = $bank_account_info['bank_full_name'];
        $request['bank_code'] = $bank_account_info['bank_code'];

        //用户可提现余额
        $user_info = db('teacher')->where('teacher_id='.$request['user_id'])->field('teacher_bonus')->find();

        //提现手续费
        $service_cost = $wx::wxWithdrawalsServiceCost($request['total_amount']);

        if($request['total_amount'] / 100 > $user_info['teacher_bonus']){
            return show(config('code.error'),'输入的金额不正确！');
        }elseif(bcsub($user_info['teacher_bonus'],$request['total_amount'] / 100,2) < $service_cost / 100){
            return show(config('code.error'),'剩余余额不足以支付手续费 ¥ '.($service_cost / 100).',当前最大可提现金额为 ¥ '.(($user_info['teacher_bonus'] - $wx::wxWithdrawalsServiceCost($user_info['teacher_bonus'] * 100) / 100) < 0 ? 0 : ($user_info['teacher_bonus'] - $wx::wxWithdrawalsServiceCost($user_info['teacher_bonus'] * 100) / 100)),['total_amount' => ($user_info['teacher_bonus'] - $wx::wxWithdrawalsServiceCost($user_info['teacher_bonus'] * 100) / 100) < 0 ? 0 : ($user_info['teacher_bonus'] - $wx::wxWithdrawalsServiceCost($user_info['teacher_bonus'] * 100) / 100),'service_cost' => $service_cost],'10000');
        }

        //提现金额正确返回
        $return = [
            //当前提现金额
            'total_amount' => $request['total_amount'],

            //提示信息
            'service_cost' => $service_cost,
        ];

        //支付密码
        $pay_password = db('user')->where('id='.$request['user_id'])->field('pay_password')->find();

        if(empty($request['pay_password'])){
            return show(config('code.error'), '你还未输入支付密码！',$return,'10001');
        }

        if(md5($request['pay_password']) != $pay_password['pay_password']){
            return show(config('code.error'), '支付密码不正确！');
        }

        //生成流水号
        $request['account_sn'] = date('YmdHis').rand(1000,9999);

        //微信提现统一入口返回信息
        $array = \wxpay\request\WxWithdrawals::query($request);

        //提现判断
        if($array['return_code'] == 'SUCCESS'){

            if($array['result_code'] == 'FAIL'){

                return show(config('code.error'),$array['return_msg'].'！'.$array['err_code_des']);
            }else{

                $m = new Account();

                Db::startTrans();

                try{

                    $money['teacher_bonus'] = $user_info['teacher_bonus'] - ($service_cost + $array['amount']) / 100;

                    $save = db('teacher')->where('teacher_id='.$request['user_id'])->update($money);

                    if($save){
                        //插入相关信息到流水记录表
                        $m::addAccount($request['account_sn'],$request['user_id'],'教师课时费用提现',-$array['amount'] / 100,3,'wx',2,1);

                        //发送消息通知
                        SendMessage($request['user_id'],'教师课时费用提现',date('Y-m-d H:i:s').'教师奖金提现成功！ 订单号【'.$request['account_sn'].'】请留意银行卡到账记录或在我的提现记录查询！');

                        Db::commit();

                        return show(config('code.success'),'申请提现成功！');
                    }else{
                        return show(config('code.error'),'申请提现失败！');
                    }
                }catch(\Exception $e){

                    Log::write($e->getMessage()."\r\n".json_encode($array));
                    Db::rollback();
                    throw new ApiException($e->getMessage(),500);
                }
            }
        }else{
            return show(config('code.error',$array['return_msg']));
        }
    }

    /**
     * 获取所有记录信息
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function getAllLessonByTeacher($where){

        $lesson = Db::name("lesson")
            ->alias('le')
            ->join('subject s','le.subject_id = s.id','LEFT')
            ->join('lesson_program p','le.program_id = p.id','LEFT')
            ->join('user user','le.teacher_id = user.id','LEFT')
            ->join('classroom cla','le.classroom_id = cla.id','LEFT')
            ->join('service_target tar','le.service_target_id = tar.id','LEFT')
            ->join('class css','le.class_id = css.id','LEFT')
            ->join('lesson_nature na','le.lesson_nature_id = na.id','LEFT')
            ->join('start_lesson sle','le.start_lesson_id = sle.id','LEFT')
            ->where($where)
            ->order('le.id desc')
            ->field('le.*,s.subject,p.program_full_name,p.program,le.lesson_name,tar.service_target,css.class_type,
                        na.lesson_nature,lesson_start_time,le.lesson_sn,le.lesson_cost,le.max_person,
                        le.lesson_num,le.lesson_method,le.one_lesson_time,le.lesson_status,le.teacher_group_images
                        ,le.teacher_group_description,le.lesson_feature,le.adapt_crowd,le.add_description,
                        le.registration_end_time,le.lesson_time_description,le.is_approve,user.full_name as teacher_name,
                        le.grade_id')
            ->select();
        if($lesson){
            foreach($lesson as $key =>$val){
                if(!empty($lesson[$key]['teacher_group_images'])){
                    $lesson[$key]['teacher_group_images'] = json_decode(htmlspecialchars_decode($lesson[$key]['teacher_group_images']));
                }
            }
        }
        return $lesson;
    }

    /**
     * 查询单条信息
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function getTeacherInformation($user_id){
        $where = "tea.teacher_id=".$user_id;

        $info = $this
            ->alias('tea')
            ->join('user u', 'tea.teacher_id=u.id', 'LEFT')
            ->join('address add','tea.teacher_id = add.member_id','LEFT')
            ->join('area area','add.area_code = area.code','LEFT')
            ->join('city city','area.citycode = city.code','LEFT')
            ->join('teacher_rank rank', 'tea.teacher_rank_id=rank.id', 'LEFT')
            ->field('tea.id,u.full_name,u.username,u.nickname,u.pay_password,u.password,u.pay_password,u.tel,u.sex,tea.teacher_bonus,tea.teacher_card_id,tea.teacher_id,rank.teacher_rank,u.rec_bonus,tea.teacher_rank_id,add.address,add.area_code,city.name as city_name')
            ->where($where)
            ->find();
        if($info){
            $info = $info -> toArray();
        }

        return $info;
    }
    /**
     * @教师端：查询当前教师所发布的并且审核通过的课程
     * @param id  int 教师用户id 必传
     * @param status int 1查询审核通过的课程 未传是查询所发布的所有课程 。选传
     * @author 巫玉梅 <1120504614@qq.com>
     */
    public function all_teacher_lessons(){
        $data = $_POST;
        if(empty($data)){

            throw new ApiException('数据不合法',404);
        }
        if(empty($data['id'])){

            throw new ApiException('id is not found',404);

        }
        if(!empty($data['status']) && $data['status'] == 1){
            $where['le.teacher_id'] = $data['id'];
            $where['le.is_approve'] = 1;
        }else{
            $where['le.teacher_id'] = $data['id'];
        }

        try{
            $info = $this->getAllLessonByTeacher($where);

            if($info){
                return show(config('code.success'),'获取数据成功',$info,200);
            }else{
                return show(config('code.error'),'未获取相关数据信息！');
            }
        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * 教师信息获取
     * @param id int 教师id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function getTeacher(){
        $data = $_GET;

        if(empty($data)) {

            throw new ApiException('数据不合法',404);
        }

        if(!isset($data['id'])){
            throw new ApiException('id is not found',404);
        }

        try{

            $teacher = $this->getTeacherInformation($data['id']);

            return show(config('code.success'),'获取教师信息成功！',$teacher);

        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }


}